const basicAuth = require('basic-auth');
const jwt = require('jsonwebtoken')
const {
  security
} = require('../config/config.js');
const {
  Forbbiden
} = require('../core/httpError.js');
class Auth {
  constructor() {

  }

  get m () {
    return async (ctx, next) => {
      const token = basicAuth(ctx.req);
      let errMsg = 'token 不合法';
      console.log('token', token);
      if (!token || !token.name) {
        throw new Forbbiden(errMsg);
      }

      try {
        var decode = jwt.verify(token.name, security.secretKey)
      } catch (err) {
        if (err.name == 'TokenExpiredError') {
          errMsg = 'token 已过期';
        };
        throw new Forbbiden(errMsg);
      }
      ctx.auth = {
        uid: decode.uid,
        scope: decode.scope
      }
      // ctx.body = token;
      await next();
    }
  }

  static verifyToken(token){
    try {
      jwt.verify(token, security.secretKey)
    } catch(err){
      return false
    }
  }
}

module.exports = {
  Auth
};